//
//  HHQRefreshControl.swift
//  HomeSchoolDemo
//
//  Created by rimi on 16/10/9.
//  Copyright © 2016年 黄华强. All rights reserved.
//

import UIKit

//临界点
let  criticalPoint: CGFloat = 80

enum HHQRefreshState {
    case nomol
    case pulling
    case willRefresh
}

class HHQRefreshControl: UIControl {
    
    //记录父视图
    fileprivate weak var scrollView: UIScrollView?
    //创建UI属性
    let refreshV = HHQRefreshView.refreshV()
    
    init() {
        super.init(frame: CGRect())
        //设置UI
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    //获得父类属性
    //这个方法是在执行addSubview会调用，移除时也会调用
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        //判断一下
        guard let sv = newSuperview as? UIScrollView else {
            return
        }
        //记录父视图
        scrollView = sv
        //使用kvo添加父视图属性变化
        //kvo添加监听以后必须在当前视图销毁前移除，否则会直接崩溃
        //通知不移除时不会发生什么，但是会造成内存泄露或重复添加
        sv.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        
    }
    //当前视图从父视图移除时会调用
    override func removeFromSuperview() {
        //必须在执行父类方法前
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        super.removeFromSuperview()
    }
    
    //kvo的监听回调方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let sv = scrollView else {
            return
        }
        let H = -(sv.contentOffset.y + sv.contentInset.top)
        
        if H < 0 {
            return
        }
        
        if sv.isDragging {
            if H > criticalPoint && refreshV.refreshState == .nomol{
                refreshV.refreshState = .pulling
               
            } else if H < criticalPoint && refreshV.refreshState == .pulling{
                refreshV.refreshState = .nomol
            }
        } else {
            
            if refreshV.refreshState == .pulling {
                //发送事件消息
                sendActions(for: .valueChanged)
            }
        }
        
        //设置控件高度
        self.frame = CGRect(x: 0, y: -H, width: UIScreen.main.bounds.width, height: H)
    }
    
    func beginRefreshing(){
        guard let sv = scrollView else {
            return
        }
        if refreshV.refreshState == .willRefresh {
            return
        }
        refreshV.refreshState = .willRefresh

        //保持刷新状态
        var inset = sv.contentInset
        inset.top += criticalPoint
        
        sv.contentInset = inset
    }
    
    func endRefreshing(){
        guard let sv = scrollView else {
            return
        }
        
        if refreshV.refreshState != .willRefresh {
            return
        }
        
        var inset = sv.contentInset
        inset.top -= criticalPoint
        UIView.animate(withDuration: 0.25, animations: {
            sv.contentInset = inset
            }) { (_) in
              self.refreshV.refreshState = .nomol
        }
        
    }
    
}

extension HHQRefreshControl {
    fileprivate func setupUI() {
        
        addSubview(refreshV)
        backgroundColor = UIColor(patternImage: UIImage(named: "refreshbg")!)
        //裁剪超出边界的图片
       // clipsToBounds = true
        //使用原生的约束框架,必须先关掉系统的自动约束, storyboard会自动关闭，
        refreshV.translatesAutoresizingMaskIntoConstraints = false
        //设置中心x
        addConstraint(NSLayoutConstraint(item: refreshV,
                                         attribute: .centerX,
                                         relatedBy: .equal,
                                         toItem: self,
                                         attribute: .centerX,
                                         multiplier: 1.0,
                                         constant: 0))
        //设置
        addConstraint(NSLayoutConstraint(item: refreshV,
                                         attribute: .bottom,
                                         relatedBy: .equal,
                                         toItem: self,
                                         attribute: .bottom,
                                         multiplier: 1.0,
                                         constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshV,
                                         attribute: .width,
                                         relatedBy: .equal,
                                         toItem: nil,
                                         attribute: .notAnAttribute,
                                         multiplier: 1.0,
                                         constant: UIScreen.main.bounds.width * 0.8))
        
        addConstraint(NSLayoutConstraint(item: refreshV,
                                         attribute: .height,
                                         relatedBy: .equal,
                                         toItem: nil,
                                         attribute: .notAnAttribute,
                                         multiplier: 1.0,
                                         constant: refreshV.bounds.height))
        
    }
}

